package com.shao.web;

import com.shao.pojo.User;
import com.shao.service.UserService;
import com.shao.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2021/5/12
 * Time: 10:51
 * Description: No Description
 */
public class RegistServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        //验证码是否正确
        if("abcde".equalsIgnoreCase(code)){
            //检查用户名是否可用
            if(userService.existsUsername(username)){
                System.out.println("用户名已经存在");
                //把错误信息和要回显的表单项信息，保存到request域中（键值对对象）
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                //跳回注册页面代码
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else{
                //可用，调用saveUser保存到数据库
                userService.registUser(new User(null,username,password,email));
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }else{
            //不正确，跳回注册页
            System.out.println("验证码"+code+"不正确");
            //把错误信息和要回显的表单项信息，保存到request域中（键值对对象）
            req.setAttribute("msg","验证码不正确");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }

    }
}
